/*
 * Copyright (c) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.huawei.health.ecology.fa.utils;

import com.huawei.healthecology.data.HealthEcologyException;

import lombok.NonNull;
import ohos.global.resource.NotExistException;
import ohos.global.resource.WrongTypeException;

import java.io.IOException;
import java.util.function.Function;

/**
 * To wrap the function that throws resource acquisition exceptions
 */
public interface OhosResourceAttempt {
    /**
     * Apply the function and throw the exceptions
     *
     * @param <T> the type parameter
     * @param <R> the type parameter
     * @param function the function need to be checked
     * @return the function has been checked
     */
    static <T, R> Function<T, R> apply(@NonNull ResourceExceptionChecker<T, R> function) {
        return inputParameter -> {
            try {
                return function.apply(inputParameter);
            } catch (NotExistException | WrongTypeException | IOException exception) {
                throw new HealthEcologyException("Acquire resource exception.");
            }
        };
    }

    /**
     * Apply the function and handle the exceptions
     *
     * @param <T> the type parameter
     * @param <R> the type parameter
     * @param resourceExceptionChecker the function need to be checked
     * @param exceptionHandler the handler to deal with the exceptions
     * @return the function has been checked
     */
    static <T, R> Function<T, R> apply(@NonNull ResourceExceptionChecker<T, R> resourceExceptionChecker,
        @NonNull Function<Exception, R> exceptionHandler) {
        return inputParameter -> {
            try {
                return resourceExceptionChecker.apply(inputParameter);
            } catch (NotExistException | WrongTypeException | IOException exception) {
                return exceptionHandler.apply(exception);
            }
        };
    }
}
